package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //定时处理未支付订单
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //获得仍未支付的订单
        List<Orders> ordersList=orderMapper.getByStatusAndTime(Orders.PENDING_PAYMENT,time);
        if (ordersList!=null&&ordersList.size()>0) {
            //再是修改订单的状态、取消原因、取消时间
            for(Orders orders:ordersList){
                Orders o=Orders.builder()
                        .id(orders.getId())
                        .cancelTime(LocalDateTime.now())
                        .status(Orders.CANCELLED)
                        .cancelReason("订单超时")
                        .build();
                orderMapper.update(o);
            }
        }
    }
    //定时处理仍在派送中的订单
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        LocalDateTime time=LocalDateTime.now().minusMinutes(60);
        //获得派送超时的订单
        List<Orders> list = orderMapper.getByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);
        //还需要判断是否存在这样的订单
        if (list!=null&&list.size()>0) {
            //修改状态
            for(Orders orders:list){
                Orders o=new Orders();
                o.setStatus(Orders.COMPLETED);
                o.setId(orders.getId());
                orderMapper.update(o);
            }
        }
    }
}
